var orgBanImg = [];
$().ready(function() {
    $("#searchProvince").click(()=>{
        handleSearchProvince()
    })
    //省
    $('#adre').citys({province:$("#provinceHidden").val()});
	validateRule();
    // select();
    $("#type").val($("#typeHidden").val());
    $("#schoolNature").val($("#schoolNatureHidden").val());

    if ($("#typeHidden").val() == 0){
        $(".company").css("display" , "block");
    }else {
        $(".company").css("display" , "none");
    }

    if ($("#typeHidden").val() == 2){
        $("#schoolType").css("display" , "block");
    }else {
        $("#schoolType").css("display" , "none");
    }


    let orgBanBox = $("#orgBanImg").val();
    console.log(orgBanBox)
    if(orgBanBox){
        let str = '';
        orgBanImg = orgBanBox.split(',');
        orgBanImg.map(function (v){
            str += `
                <div class="closeBtn">
                    <img class="upImg" src="${v}" width="95"/>
                    <span class="iconclose"><img src="../../../img/close.png"></span>
                </div>
            `;
        })
        $("#orgImg").html(str);
        touchShut(orgBanImg);
    }

    $("#introduce_sn").html($("#introduce").val())

    $('#introduce_sn').summernote({
        height: '300px',
        lang: 'zh-CN',
        toolbar: [
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['fontsize', ['fontsize']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['table', ['table']],
            ['insert', ['link', 'picture']],
            ['view', ['fullscreen', 'codeview', 'help']]
        ],
        callbacks: {
            onImageUpload: function (files, editor, $editable) {
                sendFiles(files,'#introduce_sn');
            },
        }
    });
    function handleSearchProvince(){
        console.log($('#name').val())
        if(!$('#name').val()){
            parent.layer.alert("请先填写机构名称后查询");
            return false;
        }
        $.ajax({
            data : {
                name:$('#name').val()
            },
            type : "GET",
            url : "/jzweb/organizationNews/selectProvince",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
            dataType : "json",
            success: function(data) {//data是返回的hash,key之类的值，key是定义的文件名
                console.log(data)
                if(data.data=='API Response Error : Internal Service Error:无相关结果'){
                    parent.layer.alert("无相关结果");
                    $('#province').val('')
                }else {
                    $('#province').val(data.data)
                }
            },
            error:function(data){
                //console.log("data",data)
                alert("上传失败");
            }
        });
    }
    function sendFiles(files, editor, $editable) {
        var formData = new FormData();
        formData.append("file", files[0]);
        $.ajax({
            data : formData,
            type : "POST",
            url : "/common/sysFile/upload",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
            cache : false,
            contentType : false,
            processData : false,
            dataType : "json",
            success: function(data) {//data是返回的hash,key之类的值，key是定义的文件名
                $(editor).summernote('insertImage',data.data);
            },
            error:function(data){
                //console.log("data",data)
                alert("上传失败");
            }
        });
    }


});

function touchShut(orgBanImg){

    $(".iconclose").click(function (){
        str = '';

        orgBanImg.splice($(this).index() - 1,1);
        $("#orgBanImg").val(orgBanImg.join(','));
        $(this).parent('.closeBtn').remove();

    })

}

$("#type").change(function () {
    typeChange($(this).val())
});

$("#schoolNature").val($("#schoolNatureHidden").val())

//企业和学校采集字段的区别
function typeChange(name) {

    if (name == 0){
        $(".company").css("display" , "block");
    }else {
        $(".company").css("display" , "none");
    }
    // schoolType
    if (name == 2){
        $("#schoolType").css("display" , "block");
    }else {
        $("#schoolType").css("display" , "none");
    }
}

$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});
//分页下拉框
// function select() {
//     $('#selectPage').selectPage({
//         showField : 'mobile',
//         keyField : 'id',
//         data :'/sys/user/list',
//         searchField:'name',
//         //格式化显示项目，提供源数据进行使用
//         formatItem : function(data){
//             return data.name + '(' + data.mobile + ')';
//         },
//         eAjaxSuccess : function(d){
//             var result;
//             if(d) result = d.data;
//             else result = undefined;
//             return result;
//         }
//     });
// }
function update() {
    /*if($("#selectPage").val()==''){
        layer.msg("负责人不能为空");
        return false
    }*/
    // $('#province').prop('disabled', false);
    $("#introduce").val($('#introduce_sn').summernote('code'));

	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/organizationNews/update",
		data : $('#signupForm').serialize(),// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
            // $('#province').prop('disabled', true);
		},
		success : function(data) {
            // $('#province').prop('disabled', true);
			if (data.code == 0) {
				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
        rules : {
            type : {
                required : true
            },
            name : {
                required : true
            },
            schoolNature : {
                required : true
            },
            introduce : {
                required : true
            },
            province : {
                required : true
            },
        },
        messages : {
            type : {
                required : icon + "请选择机构类型"
            },
            name : {
                required : icon + "请输入机构名称"
            },
            schoolNature : {
                required : icon + "请输入学校类别"
            },      introduce : {
                required : icon + "请输入机构介绍"
            },
            province : {
                required : icon + "请输入省份"
            },
		}
	})
}
layui.use('upload', function () {
    var upload = layui.upload;
    upload.render({
        elem: '#btnUpload',
        url: '/common/sysFile/upload',
        accept: 'images', //只允许上传图片
        acceptMime: 'image/*', //只筛选图片
        size:1024,
        done: function (r) {
            $("#orgPhoto").val(r.data);
            $("#img").attr("src",r.data)
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});

layui.use('upload', function () {
    var upload = layui.upload;
    upload.render({
        elem: '#btnUpload1',
        url: '/common/sysFile/upload',
        accept: 'images', //只允许上传图片
        acceptMime: 'image/*', //只筛选图片
        size:1024,
        done: function (r) {
            $("#cachet").val(r.data);
            $("#img1").attr("src",r.data)
        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});


layui.use('upload', function () {
    var upload = layui.upload;
    upload.render({
        elem: '#orgImgBox',
        url: '/common/sysFile/upload',
        accept: 'images', //只允许上传图片
        acceptMime: 'image/*', //只筛选图片
        multiple:true,
        done: function (r) {
            str = '';
            orgBanImg.push(r.data);
            orgBanImg.map(function (v){
                str += `
                    <div class="closeBtn">
                        <img class="upImg" src="${v}" width="95"/>
                        <span class="iconclose"><img src="../../../img/close.png"></span>
                    </div>
                `;
            })

            $("#orgImg").html(str);
            $("#orgBanImg").val(orgBanImg.join(','));
            touchShut(orgBanImg);

        },
        error: function (r) {
            layer.msg(r.msg);
        }
    });
});